export default {
  state: {
    login: false, // 是否登录
    userInfo: {}, // 用户信息
    isSign: false, // 是否签到
    mobile: false // 是否绑定手机号
  },
  getters: {
    login: (state) => state.login,
    userInfo: (state) => state.userInfo,
    isSign: (state) => state.isSign,
    mobile: (state) => state.mobile,
    isVip: (state) => {
      return state.userInfo?.level == "2"
    }
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, data) {
      if (data) {
        state.login = true
        state.userInfo = data
        state.mobile = data.mobile ? true : false
        uni.setStorageSync("userInfo", data)
      }
    },
    // 设置签到信息
    SET_USER_SIGN(state, data) {
      state.isSign = data.todaySign == 1
      uni.setStorageSync("isSign", data.todaySign)
    },

    // 清除用户信息
    CLEAR_USER_INFO(state) {
      state.login = false
      state.isSign = false
      state.mobile = false
      state.userInfo = {}
      uni.removeStorageSync("userInfo")
      uni.removeStorageSync("isSign")
    }
  },
  actions: {
    // 获取用户信息
    async getUserInfo({ commit }, params = {}) {
      try {
        const data = await uni.$api.user.userInfo({}, { handleError: false, ...params, queue: "sync" })
        commit("SET_USER_INFO", data)
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取签到信息
    getUserSign({ commit }) {
      uni.$api.user.getHistoryDoSign().then((data) => {
        commit("SET_USER_SIGN", data)
      })
    },
    // #ifdef MP-WEIXIN
    // 微信小程序静默登录
    async wxMpSilentLogin({ dispatch }) {
      return new Promise(async (resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            const data = JSON.stringify({ code: res.code })
            uni.$api.public
              .loginByOAuth2({ data, type: "weixin" }, { handleError: false, queue: "sync" })
              .then(() => {
                dispatch("getUserInfo")
                resolve(data)
              })
              .catch((err) => {
                reject(err)
              })
          }
        })
      })
    },
    // #endif
    // 清除用户信息
    clearUserInfo({ commit }) {
      commit("CLEAR_USER_INFO")
    },

    // 退出登录
    async logout({ commit, dispatch }) {
      try {
        commit("CLEAR_USER_INFO")
        await dispatch("clearToken")
        await dispatch("getToken")
        uni.$emit("logout-success")
        dispatch("getChannelInfo")
        dispatch("getMyDecoInfo")
        dispatch("getIndexDecoInfo")
        dispatch("getVipOneDecoInfo")
        dispatch("getVipTwoDecoInfo")
        dispatch("getProblemDecoInfo")
        return Promise.resolve(true)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
}
